pub mod log_info;

use std::fs::create_dir_all;
use std::str::FromStr;
use std::sync;
use once_cell::sync::Lazy;
use log_info::LogInfo;
use crate::config::run_setup::log_level::LogLevel;
use crate::config::run_setup::RUN_SETUP_CONFIG;

static PRINT_LOG_VEC: Lazy<sync::Mutex<Vec<LogInfo>>> = Lazy::new(|| {
  sync::Mutex::new(Vec::new())
});

pub fn push(log_level: LogLevel, message: String) {
  let mut guard = PRINT_LOG_VEC.lock().expect("cannot lock PRINT_LOG_VEC");
  guard.push(LogInfo::build(log_level, message));
}

pub fn push_error(message: String) {
  push(LogLevel::Error, message);
}

pub fn push_info(message: String) {
  push(LogLevel::Info, message);
}

pub fn push_dev(message: String) {
  push(LogLevel::Dev, message);
}

pub fn get_log_content() -> String {
  let guard = PRINT_LOG_VEC.lock().expect("cannot lock PRINT_LOG_VEC");
  let mut result = String::new();
  for log_info in guard.iter() {
    let log_text = log_info.to_text();
    result.push_str(log_text.as_str());
    result.push_str("\n\n\n\n");
  }
  return result;
}

pub fn write_log_in(file_path: &str) {
  let file_content = get_log_content();
  std::fs::write(file_path, file_content.as_bytes()).expect(
    format!("write cache log error!!:: {file_path} ").as_str()
  );
}

pub fn write_default_log() {
  let run_setup = &RUN_SETUP_CONFIG;
  let log_cache = run_setup.log_cache.as_str();
  let file_name = chrono::Local::now().format("rust-log-%Y-%m-%d_%H_%M_%S.txt");
  let cache_file = format!(
    "{log_cache}/{file_name}"
  );
  let cache_file_path = cache_file.as_str();
  let path_buf = std::path::PathBuf::from_str(cache_file_path).expect(
    format!("cannot as path buf: [{}]", cache_file_path).as_str()
  );
  let dir_buf = path_buf.parent().expect("cache directory is not found");
  if !dir_buf.exists() {
    let dir_path = dir_buf.to_str().unwrap();
    create_dir_all(dir_path).expect(
      format!("cannot create_dir_all: {}", dir_path).as_str()
    );
  }
  write_log_in(cache_file_path);
  println!("write cache file in {}", cache_file_path);
}
